package com.movie.controller.SysUserController;

import com.movie.beans.SysUser;
import com.movie.beans.base.AjaxResult;
import com.movie.service.SysPasswordService;
import com.movie.service.UserService;
import com.movie.utils.DateUtils;
import com.movie.utils.ShiroUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping(value = "/system/user/profile")
public class ProfileController {

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private UserService userService;

    private String prefix="/system/user/profile";
    @GetMapping()
    public String profile(ModelMap mmap){
        SysUser user = ShiroUtil.getSysUser();
        mmap.put("user", user);
        return prefix+"/profile";
    }

    @GetMapping(value = "/resetPwd")
    public String resetPwd(){
        return prefix+"/resetPwd";
    }


    @PostMapping(value = "/resetPwd")
    @ResponseBody
    public AjaxResult resetPwd(String oldPassword,String newPassword){
        SysUser user = ShiroUtil.getSysUser();
        if (!passwordService.matches(user, oldPassword))
        {
            return AjaxResult.error("修改密码失败，旧密码错误");
        }
        if (passwordService.matches(user, newPassword))
        {
            return AjaxResult.error("新密码不能与旧密码相同");
        }
        user.setSalt(ShiroUtil.randomSalt());
        user.setPassword(passwordService.encryptPassword(user.getLoginName(), newPassword, user.getSalt()));
        user.setPwdUpdateTime(DateUtils.getNowDate());
        if (userService.resetUserPwd(user) > 0)
        {
            ShiroUtil.setSysUser(userService.selectUserById(user.getUserId()));
            return AjaxResult.success("修改密码成功");
        }
        return AjaxResult.error("修改密码异常，请联系管理员");
    }
    @PostMapping("/update")
    public @ResponseBody AjaxResult update(SysUser user)
    {
        if(userService.updateUser(user)>0)
        {
            ShiroUtil.setSysUser(userService.selectUserById(user.getUserId()));
            return AjaxResult.success("保存成功");
        }
        else {
            return AjaxResult.error("保存失败");
        }

    }
}
